package com.dwusoft.banks.controller;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import utils.Constants;
import utils.SM2Utils;

import com.alibaba.fastjson.JSON;
import com.dwusoft.banks.model.TransInput;
import com.google.gson.Gson;

@Controller
@RequestMapping("/file")
public class FileController {
	
	private final static Logger logger = LoggerFactory.getLogger(FileController.class);
	
	@RequestMapping(value = "{action}",method = RequestMethod.GET)
	public void p2pHome(ModelMap modelMap,HttpServletRequest request){
		String base = request.getContextPath();
		String fullPath = request.getScheme()+"://" + request.getServerName() +":"+ request.getServerPort() + base;
		logger.info("访问： "+fullPath);
		modelMap.addAttribute("base", base);
	}
	
	
	@RequestMapping(value = "{actionURL}",method = RequestMethod.POST)
	public String createAccount(TransInput transInput,ModelMap model,HttpServletRequest request){
		logger.info(transInput.toString());
		//1.生成请求业务对象
		logger.info("================step 1  生成请求业务对象=================");
		String sign = "";
		String body = req2str(request,transInput);
		logger.info("Context： "+body);
		
		//2.生成报文头
		logger.info("================step 2  生成签名=================");
		try {
			sign = SM2Utils.signRaw(body, transInput.getSecuNo());
			logger.info("签名值：" + sign);
		} catch (Exception e) {
			logger.info("生成签名失败");
			e.printStackTrace();
		}
		
		//3.生成密文
		logger.info("================step 3  生成密文=================");
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put(Constants.SIGN_NAME, sign);
		paramMap.put(Constants.BODY_NAME, body);
		
		String plainTxt = JSON.toJSONString(paramMap);	//待加密字符串
		logger.info("明文：" + plainTxt);
		
		String cipherTxt = "";//密文
		try {
			cipherTxt = SM2Utils.encrypt(plainTxt);
			logger.info("密文：" + cipherTxt);
		} catch (Exception e) {
			logger.info("加密失败");
			e.printStackTrace();
		}
		
		
		logger.info("================step 4 返回前台，调整资金托管平台 =================");
		model.addAttribute(Constants.CONTEXT_NAME, cipherTxt);
		model.addAttribute("actionURL", Constants.NET_TRADE_PLATFORM_URL+request.getServletPath());
		
		return "redirect";
	}
	
	
	private String req2str(HttpServletRequest request,TransInput transInput){
		Map<String, Object> retMap = new HashMap<String, Object>();
		Map<String, String[]>  params = request.getParameterMap();
		for(String key : params.keySet()){
			try {
				Field field = TransInput.class.getDeclaredField(key);
				if(key.equalsIgnoreCase(field.getName())){
					//System.out.println("+++++++"+field.getName());
					continue;
				}
			}catch (Exception e) {}
			
			String value = params.get(key)[0];
			if(value.length()==0 || "".equals(value)){
				continue;
			}
			retMap.put(key, value);
			
		}
		
		SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sf2 = new SimpleDateFormat("hhmmss");
		
		transInput.setTransDate(sf1.format(new Date()));
		transInput.setTransTime(sf2.format(new Date()));
		
		retMap.put("transInput", transInput);
		
		Gson gson = new Gson();
		
		return gson.toJson(retMap);
		
//		return JSON.toJSONString(retMap);
	}
	
}
